package cn.zh.stan.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import cn.zh.stan.BaseUrl;
import cn.zh.stan.MyApplication;
import cn.zh.stan.R;
import cn.zh.stan.Zf.PayResult;
import cn.zh.stan.util.ToastUtil;
import cn.zh.stan.widget.Keyboard;
import cn.zh.stan.widget.PayEditText;
import cn.zh.stan.wxapi.WXPayEntryActivity;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

public class ToPay extends BaseActivity {

    LinearLayout pchalin,pzflin,pwxlin;
    ImageView pcharge,pzfimg,pwximg,tpback;
    int type=0;
    Button paybtn;
    String tradeNo="",tomon="";
    MyApplication mapp;
    String uid;
    PopupWindow popupWindow;
    Dialog dialog;
    private static final String[] KEY = new String[] {
            "1", "2", "3",
            "4", "5", "6",
            "7", "8", "9",
            "<<", "0", "完成"};
    private PayEditText payEditText;
    private Keyboard keyboard;
    String psword="";
    private static final int SDK_PAY_FLAG = 1;
    TextView retxt;


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        mapp.setIspay(true);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        mapp.setIspay(false);
                     }
                    Intent intent=new Intent(ToPay.this, WXPayEntryActivity.class);
                    startActivity(intent);
                    finish();
                    break;
                }
                default:
                    break;
            }
        };
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_to_pay);
        tradeNo=getIntent().getStringExtra("tradeNo");
        tomon=getIntent().getStringExtra("tomon");
        mapp= (MyApplication) getApplication();
        uid=mapp.getSp().getString("uid","");
        initt();
         }

    public void initt(){
        pchalin= (LinearLayout) findViewById(R.id.pchalin);
        pzflin= (LinearLayout) findViewById(R.id.pzflin);
        pwxlin= (LinearLayout) findViewById(R.id.pwxlin);
        pcharge= (ImageView) findViewById(R.id.pcharge);
        pzfimg= (ImageView) findViewById(R.id.pzfimg);
        pwximg= (ImageView) findViewById(R.id.pwximg);
        paybtn= (Button) findViewById(R.id.paybtn);
        tpback= (ImageView) findViewById(R.id.tpback);
        retxt= (TextView) findViewById(R.id.retxt);
        pchalin.setOnClickListener(this);
        pzflin.setOnClickListener(this);
        pwxlin.setOnClickListener(this);
        paybtn.setOnClickListener(this);
        tpback.setOnClickListener(this);
        retxt.setText("¥"+tomon);
        pcharge.setBackgroundResource(R.mipmap.round_check_fill);
         }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        int id=view.getId();
        switch (id){
            case R.id.pchalin:
                type=0;
                pcharge.setBackgroundResource(R.mipmap.round_check_fill);
                pzfimg.setBackgroundResource(R.mipmap.round);
                pwximg.setBackgroundResource(R.mipmap.round);
                break;
            case R.id.pzflin:
                type=1;
                pzfimg.setBackgroundResource(R.mipmap.round_check_fill);
                pcharge.setBackgroundResource(R.mipmap.round);
                pwximg.setBackgroundResource(R.mipmap.round);
                break;
            case R.id.pwxlin:
                type=2;
                pwximg.setBackgroundResource(R.mipmap.round_check_fill);
                pcharge.setBackgroundResource(R.mipmap.round);
                pzfimg.setBackgroundResource(R.mipmap.round);
                break;
            case R.id.paybtn:
                //调起支付
                switch (type){
                    case 0://余额支付
                        getPopu();
                        break;
                    case 1://支付宝支付
                        getaPpli();
                        break;
                    case 2://微信支付

                        break;
                     }
                break;
            case R.id.tpback:
                finish();
                break;
            case R.id.ocancle:
                dialog.dismiss();
                break;
            case R.id.osure:
                Intent intent=new Intent(ToPay.this,ReCharge.class);
                startActivity(intent);
                break;
            }
          }


    private void initEvent() {
        keyboard.setOnClickKeyboardListener(new Keyboard.OnClickKeyboardListener() {
            @Override
            public void onKeyClick(int position, String value) {
                if (position < 11 && position != 9) {
                    payEditText.add(value);
                } else if (position == 9) {
                    payEditText.remove();
                } else if (position == 11) {
                    //当点击完成的时候，也可以通过payEditText.getText()获取密码，此时不应该注册OnInputFinishedListener接口
                    getbalan(psword);
                    popupWindow.dismiss();
                }
               }
           });

        /**
         * 当密码输入完成时的回调
         */
        payEditText.setOnInputFinishedListener(new PayEditText.OnInputFinishedListener() {
            @Override
            public void onInputFinished(String password) {
                System.out.println("---------->支付密码==="+password);
                psword=password;
              }
          });
         }

    //余额支付
     public void getbalan(String pass){
         OkHttpUtils.post(BaseUrl.SurplusPay)
                 .params("userId",uid)
                 .params("tradeNo",tradeNo)
                 .params("payPwd",pass)
                 .execute(new StringCallback() {
                     @Override
                     public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                         try {
                             JSONObject js=new JSONObject(s);
                             boolean State=js.getBoolean("State");
                             if (State){
                                 boolean Flag=js.getBoolean("Flag");
                                 if (Flag){
                                   mapp.setIspay(true);
                                   Intent intent=new Intent(ToPay.this, WXPayEntryActivity.class);
                                   startActivity(intent);
                                   finish();
                                 }else {
                                 String Code=js.getString("Code");
                                 if (Code.equals("1003")){
                                   //余额不足弹窗
                                     getDialog();
                                 }
                                 }

                             }
                         } catch (JSONException e) {
                             e.printStackTrace();
                         }
                     }
                     @Override
                     public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                         super.onError(isFromCache, call, response, e);
                     }
                   });
                }

  //支付宝支付
    public void getaPpli(){
        OkHttpUtils.post(BaseUrl.AliPay)
                .params("userId",uid)
                .params("body","订单支付宝付款")
                .params("subject","订单支付")
                .params("totalAmount",tomon)
                .params("tradeNo",tradeNo)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        try {
                            JSONObject js=new JSONObject(s);
                            boolean State=js.getBoolean("State");
                            if (State){
                                boolean Flag=js.getBoolean("Flag");
                                if (Flag){
                                 final String OrderString=js.getString("OrderString");
                                    Runnable payRunnable = new Runnable() {

                                        @Override
                                        public void run() {
                                            PayTask alipay = new PayTask(ToPay.this);
                                            Map<String, String> result = alipay.payV2(OrderString, true);
                                            Log.i("msp", result.toString());
                                            Message msg = new Message();
                                            msg.what = SDK_PAY_FLAG;
                                            msg.obj = result;
                                            mHandler.sendMessage(msg);
                                        }
                                    };

                                    Thread payThread = new Thread(payRunnable);
                                    payThread.start();

                                }else {
                               String MSg=js.getString("Msg");
                                 ToastUtil.showLong(ToPay.this,MSg);
                                }
                             }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                    }
                });
              }



    public void getPopu(){
        View view1= LayoutInflater.from(this).inflate(R.layout.balayout,null,false);
        payEditText = (PayEditText)view1.findViewById(R.id.PayEditText_pay);
        keyboard = (Keyboard)view1.findViewById(R.id.KeyboardView_pay);
        ImageView dis = view1.findViewById(R.id.dis);
        final View shvi = view1.findViewById(R.id.shvi);
        keyboard.setKeyboardKeys(KEY);
        initEvent();
        dis.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
            }
        });
        popupWindow = new PopupWindow(view1, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        popupWindow.getContentView().setFocusableInTouchMode(true);
        popupWindow.getContentView().setFocusable(true);
        popupWindow.setAnimationStyle(R.style.popwinstyle);
//        WindowManager.LayoutParams lp = getWindow().getAttributes();
//        lp.alpha=0.5f;
//        getWindow().setAttributes(lp);
//
//        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
//            @Override
//            public void onDismiss() {
//                WindowManager.LayoutParams lp = getWindow().getAttributes();
//                lp.alpha=1.0f;
//                getWindow().setAttributes(lp);
//            }
//        });
        popupWindow.showAtLocation(findViewById(R.id.activity_to_pay), Gravity.BOTTOM, 0, 0);

        }


         //余额不足弹窗

    public void getDialog(){

        LayoutInflater inflater = LayoutInflater.from(this);
        View v = inflater.inflate(R.layout.out_layout, null);// 得到加载view
        LinearLayout layout = (LinearLayout) v
                .findViewById(R.id.out_layout);// 加载布局

        dialog = new Dialog(ToPay.this, R.style.MyDialogStyle);
        dialog.show();
        dialog.setContentView(layout,new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT));
        v.findViewById(R.id.ocancle).setOnClickListener(this);
        v.findViewById(R.id.osure).setOnClickListener(this);
        TextView txt=v.findViewById(R.id.dgtxt);
        txt.setText("余额不足是否充值?");
      }


    }
